import { useState, useEffect } from 'react';
import { Box, Button, Typography, Alert, Card, CardContent } from '@mui/material';
import { getDictTypeList, getDictDataEnabledByTypeCode } from 'src/api/dict-api';
import { usePaymentWays, useIncomeSources } from 'src/hooks/use-dict';

export default function DictTestPage() {
  const [dictTypes, setDictTypes] = useState<any[]>([]);
  const [paymentWays, setPaymentWays] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [apiLogs, setApiLogs] = useState<string[]>([]);

  // 使用字典 hooks
  const { data: paymentWaysFromHook, loading: hookLoading, error: hookError } = usePaymentWays();
  const { data: incomeSourcesFromHook } = useIncomeSources();

  const addLog = (message: string) => {
    setApiLogs(prev => [...prev, `${new Date().toLocaleTimeString()}: ${message}`]);
  };

  const testDictTypeAPI = async () => {
    setLoading(true);
    setError(null);
    addLog('开始测试字典类型API...');
    
    try {
      const response = await getDictTypeList();
      addLog(`字典类型API响应: ${JSON.stringify(response)}`);
      
      if (response.success) {
        setDictTypes(response.data || []);
        addLog(`成功获取 ${response.data?.length || 0} 个字典类型`);
      } else {
        setError(response.message || '获取字典类型失败');
        addLog(`API返回错误: ${response.message}`);
      }
    } catch (err) {
      const errorMsg = (err as Error).message || '未知错误';
      setError(errorMsg);
      addLog(`API调用异常: ${errorMsg}`);
    } finally {
      setLoading(false);
    }
  };

  const testDictDataAPI = async () => {
    setLoading(true);
    setError(null);
    addLog('开始测试字典数据API...');
    
    try {
      const response = await getDictDataEnabledByTypeCode('PAYMENT_WAY');
      addLog(`字典数据API响应: ${JSON.stringify(response)}`);
      
      if (response.success) {
        setPaymentWays(response.data || []);
        addLog(`成功获取 ${response.data?.length || 0} 个支付方式`);
      } else {
        setError(response.message || '获取字典数据失败');
        addLog(`API返回错误: ${response.message}`);
      }
    } catch (err) {
      const errorMsg = (err as Error).message || '未知错误';
      setError(errorMsg);
      addLog(`API调用异常: ${errorMsg}`);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    addLog('页面加载完成，hooks状态:');
    addLog(`paymentWaysFromHook: ${JSON.stringify(paymentWaysFromHook)}`);
    addLog(`incomeSourcesFromHook: ${JSON.stringify(incomeSourcesFromHook)}`);
    addLog(`hookLoading: ${hookLoading}`);
    addLog(`hookError: ${hookError}`);
  }, [paymentWaysFromHook, incomeSourcesFromHook, hookLoading, hookError]);

  return (
    <Box sx={{ p: 3 }}>
      <Typography variant="h4" sx={{ mb: 3 }}>字典功能测试页面</Typography>
      
      <Box sx={{ mb: 3 }}>
        <Button variant="contained" onClick={testDictTypeAPI} disabled={loading} sx={{ mr: 2 }}>
          测试字典类型API
        </Button>
        <Button variant="contained" onClick={testDictDataAPI} disabled={loading}>
          测试字典数据API
        </Button>
      </Box>

      {error && (
        <Alert severity="error" sx={{ mb: 2 }}>
          {error}
        </Alert>
      )}

      {hookError && (
        <Alert severity="warning" sx={{ mb: 2 }}>
          Hook错误: {hookError}
        </Alert>
      )}

      <Box sx={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 3 }}>
        <Card>
          <CardContent>
            <Typography variant="h6" sx={{ mb: 2 }}>字典类型 (API调用)</Typography>
            {dictTypes.length > 0 ? (
              <Box>
                {dictTypes.map((type) => (
                  <Typography key={type.id} sx={{ mb: 1 }}>
                    <strong>名称:</strong> {type.name} | <strong>编码:</strong> {type.code} | <strong>状态:</strong> {type.enabled === 0 ? '启用' : '禁用'}
                  </Typography>
                ))}
              </Box>
            ) : (
              <Typography color="text.secondary">暂无数据</Typography>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardContent>
            <Typography variant="h6" sx={{ mb: 2 }}>支付方式 (API调用)</Typography>
            {paymentWays.length > 0 ? (
              <Box>
                {paymentWays.map((way) => (
                  <Typography key={way.id} sx={{ mb: 1 }}>
                    <strong>名称:</strong> {way.name} | <strong>值:</strong> {way.value} | <strong>状态:</strong> {way.enabled === 0 ? '启用' : '禁用'}
                  </Typography>
                ))}
              </Box>
            ) : (
              <Typography color="text.secondary">暂无数据</Typography>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardContent>
            <Typography variant="h6" sx={{ mb: 2 }}>支付方式 (Hook)</Typography>
            {hookLoading ? (
              <Typography>加载中...</Typography>
            ) : paymentWaysFromHook.length > 0 ? (
              <Box>
                {paymentWaysFromHook.map((way) => (
                  <Typography key={way.id} sx={{ mb: 1 }}>
                    <strong>名称:</strong> {way.name} | <strong>值:</strong> {way.value} | <strong>状态:</strong> {way.enabled === 0 ? '启用' : '禁用'}
                  </Typography>
                ))}
              </Box>
            ) : (
              <Typography color="text.secondary">暂无数据</Typography>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardContent>
            <Typography variant="h6" sx={{ mb: 2 }}>收入来源 (Hook)</Typography>
            {incomeSourcesFromHook.length > 0 ? (
              <Box>
                {incomeSourcesFromHook.map((source) => (
                  <Typography key={source.id} sx={{ mb: 1 }}>
                    <strong>名称:</strong> {source.name} | <strong>值:</strong> {source.value} | <strong>状态:</strong> {source.enabled === 0 ? '启用' : '禁用'}
                  </Typography>
                ))}
              </Box>
            ) : (
              <Typography color="text.secondary">暂无数据</Typography>
            )}
          </CardContent>
        </Card>
      </Box>

      <Card sx={{ mt: 3 }}>
        <CardContent>
          <Typography variant="h6" sx={{ mb: 2 }}>API调用日志</Typography>
          <Box sx={{ maxHeight: 300, overflow: 'auto', backgroundColor: '#f5f5f5', p: 2, borderRadius: 1 }}>
            {apiLogs.map((log, index) => (
              <Typography key={index} variant="body2" sx={{ fontFamily: 'monospace', mb: 0.5 }}>
                {log}
              </Typography>
            ))}
          </Box>
        </CardContent>
      </Card>
    </Box>
  );
}
